#!env node

let path = require('path');
let fs = require('fs');

// 获取参数
let argv = process.argv;
let rootDir = process.cwd();

// 解析参数
if (argv.includes('controller')) {
    // 控制器的参数
    let index = argv.indexOf('controller');
    // 获取控制器的名称
    let controllerName = argv[index + 1];
    controllerName = controllerName.toLowerCase();
    if (!controllerName) {
        console.error('[x] 请设置控制器名称 controller /view/admin/controller/name.ts \r\n');
        process.exit(1);
    }
    controllerName = path.resolve(rootDir + '/' + controllerName);
    // 检测目录是否存在
    if (!fs.existsSync(path.dirname(controllerName))) {
        console.error(`[x] 目录${ path.dirname(controllerName)}不存在 `);
        process.exit(1);
    }
    // 创建控制器文件
    let className = (path.parse(controllerName)).name;
    className = ucfirst(className);
    let controllerData = `import BaseController from "../../core/BaseController";\r\nclass ${className} extends BaseController\r\n{\r\n\r\n}\r\n\r\nmodule.exports = ${className};`;
    fs.writeFileSync(controllerName, controllerData);
    console.info('[x] 成功创建controller ' + controllerName);
} else if (argv.includes('model')) {
    // 创建model 
    // 控制器的参数
    let index = argv.indexOf('model');
    // 获取控制器的名称
    let modelDir = argv[index + 1];
    modelDir = modelDir.toLowerCase();
    if (!modelDir) {
        console.error('[x] 请设置model名称 model /view/admin/model/name.ts \r\n');
        process.exit(1);
    }
    modelDir = path.resolve(rootDir + '/' + modelDir);
    // 检测目录是否存在
    if (!fs.existsSync(path.dirname(modelDir))) {
        console.error(`[x] 目录${ path.dirname(modelDir)}不存在 `);
        process.exit(1);
    }
    // 创建控制器文件
    let modelName = (path.parse(modelDir)).name;
    let ext = (path.parse(modelDir)).ext;
    modelName = ucfirst(modelName);
    let modelData = `import BaseModel from "../../core/BaseModel";\r\nexport default class ${modelName} extends BaseModel\r\n{\r\n\r\n}\r\n`;
    modelDir = path.dirname(modelDir) + '/' + modelName +  ext;
    console.log(modelDir);
    fs.writeFileSync(modelDir, modelData);
    console.info('[x] 成功创建model ' + path.dirname(modelDir) + '/' + modelName + '.' + ext);
} else if (argv.includes('help')) {
    console.info('[x 工具使用帮助:] \r\n\f node tools.js help --查看使用\r\n\f node tools.js controller ./src/home/controller/a.ts 创建controller文件 \r\n\f node tools.js model ./src/home/model/aaa.ts 创建model文件');
}

/**
 * 首字母大写
 */
function ucfirst(str){
    if (!str) {
        return '';
    }
    return (str.substr(0, 1)).toUpperCase() + str.substr(1);
}